package cn.lopr.im.api.controller;

import cn.lopr.im.api.annotation.Auth;
import cn.lopr.im.api.annotation.DataSource;
import cn.lopr.im.api.bean.User;
import cn.lopr.im.api.common.CallbackMessage;
import cn.lopr.im.api.common.Constant;
import cn.lopr.im.api.configuration.AuthInfo;
import cn.lopr.im.api.configuration.datasources.DynamicDataSourceEnum;
import cn.lopr.im.api.po.ArrayPo;
import cn.lopr.im.api.service.IAuthService;
import cn.lopr.im.api.service.IUserService;
import cn.lopr.im.api.utils.DateUtil;
import cn.lopr.im.api.utils.MessageHelper;
import cn.lopr.im.api.utils.jwt.JwtUtil;
import cn.lopr.im.api.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shuangyang7
 * @date 2020/12/22 18:29
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IAuthService authService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @RequestMapping("/login")
    @ResponseBody
    @DataSource(DynamicDataSourceEnum.MASTER)
    public CallbackMessage<?> login(HttpServletResponse response, String phone, String password) {

        User res = userService.login(phone, password);

        if (res == null) {
            return CallbackMessage.createByError("登录失败，请检查用户信息");
        }

        res.setPassword(null);

        String token = authService.addCache(res);

        response.addHeader("Authorization", "IM" + token);

        return CallbackMessage.createBySuccess("登录成功", new HashMap<String, Object>() {{
            put("token", "IM" + token);
            put("roles", "user");
            put("user", res);
        }});
    }

    @RequestMapping("/isLogin")
    @ResponseBody
    @Auth
    public CallbackMessage<?> isLogin() {

        User user = AuthInfo.get();

        return CallbackMessage.createBySuccess("isLogin", user);
    }

    @Auth
    @RequestMapping("/getFriend")
    public CallbackMessage<?> getFriend(String phone) {

        User user = AuthInfo.get();

        if (phone != null) {
            // TODO 测试用 最终删除
            List<User> users = userService.getFriend(new User().setPhone(phone));
            return CallbackMessage.createBySuccess(Constant.ResponseCode.SUCCESS.getDesc(), users);
        }

        List<User> users = userService.getFriend(user);
        return CallbackMessage.createBySuccess(Constant.ResponseCode.SUCCESS.getDesc(), users);
    }

    @Auth
    @RequestMapping("/getFriendByPhones")
    public CallbackMessage<?> getFriendByPhones(@RequestBody ArrayPo arrayPo) {

        if (arrayPo.getPhones() == null || arrayPo.getPhones().length == 0) {
            return CallbackMessage.createBySuccess(Constant.ResponseCode.SUCCESS.getDesc(), new ArrayList<User>());
        }
        List<User> users = userService.getFriendByPhones(arrayPo.getPhones());
        return CallbackMessage.createBySuccess(Constant.ResponseCode.SUCCESS.getDesc(), users);
    }

    @Auth
    @RequestMapping("/getCode")
    public CallbackMessage<User> getCode(String phone) {

        if (MessageHelper.SMS(phone, new String[]{String.valueOf(Math.round((Math.random() + 1) * 1000)), "3"})) {
            return CallbackMessage.createBySuccess(Constant.ResponseCode.SUCCESS.getDesc());
        }

        return CallbackMessage.createByError("注册失败，请重试");
    }

    @RequestMapping("/reg")
    public CallbackMessage<User> reg(String phone, String password, String name) {
        User reg = userService.reg(phone, password, name);

        if (reg != null) {
            return CallbackMessage.createBySuccess(Constant.ResponseCode.SUCCESS.getDesc(), reg);
        }

        return CallbackMessage.createByError("注册失败，请重试");
    }

    @RequestMapping("/regBefore")
    public CallbackMessage<?> regBefore(HttpServletResponse response, String phone, String password, String sex, String portrait, String introduction) {
        boolean isOk = userService.regBefore(new User().setPhone(phone).setPassword(password)
                .setSex(sex).setPortrait(portrait).setIntroduction(introduction));

        if (isOk) {
            User res = userService.autoLogin(phone);

            res.setPassword(null);

            String token = authService.addCache(res);

            response.addHeader("Authorization", "IM" + token);

            return CallbackMessage.createBySuccess("创建成功，即将跳转登录界面！", new HashMap<String, Object>() {{
                put("token", "IM" + token);
                put("roles", "user");
                put("user", res);
            }});
        }

        return CallbackMessage.createByError("出现了一些错误，请重试！");
    }

    @Auth
    @RequestMapping("/update")
    public CallbackMessage<?> updateUser(String nickName, String sex, String introduction, String birth) {

        User user = AuthInfo.get();

        boolean isOk = userService.updateUser(new User().setPhone(user.getPhone()).setNickname(nickName)
                .setSex(sex).setIntroduction(introduction).setBirthday(DateUtil.parseYMD(birth)));

        if (isOk) {
            return CallbackMessage.createBySuccess("您的信息更新成功！");
        }

        return CallbackMessage.createByError("出现了一些错误，请重试！");

    }

    @Auth
    @RequestMapping("/searchFriend")
    public CallbackMessage<?> searchFriend(String content) {

        User user = AuthInfo.get();

        List<UserVo> users = userService.searchFriend(user.getPhone(), content);

        if (users.size() != 0) {
            return CallbackMessage.createBySuccess(Constant.ResponseCode.SUCCESS.getDesc(), users);
        }

        return CallbackMessage.createByError("未查询到信息");
    }

    @Auth
    @RequestMapping("/addFriend")
    public CallbackMessage<?> addFriend(String content) {

        User user = AuthInfo.get();

        if (userService.addFriend(user.getPhone(), content)) {
            return CallbackMessage.createBySuccess("添加成功");
        }

        return CallbackMessage.createByError("未查询到信息");
    }

    @Auth
    @RequestMapping("/getUserInfo")
    public CallbackMessage<?> getUserInfo() {
        User user = AuthInfo.get();
        user.setPassword(null);
        return CallbackMessage.createBySuccess(user);
    }

    @Auth
    @RequestMapping("/getUserInfoById")
    public CallbackMessage<?> getUserInfoById(Integer userId) {
        User userById = userService.getUserById(userId);
        return CallbackMessage.createBySuccess(userById);
    }

    @RequestMapping("/getLikeMeLikeYouVisitPublish")
    public CallbackMessage<?> getLikeMeLikeYouVisitPublish(Integer userId) {
        User user = AuthInfo.get();
        Map<String, Integer> res = userService.getLikeMeLikeYouVisitPublish(userId);
        return CallbackMessage.createBySuccess(res);
    }

    @RequestMapping("/getUser")
    public User getUser() {
        return userService.getUser();
    }

}
